﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ExtendPropertyLib.WPF;
using ExORMDesginer.Models;
using ExtendPropertyLib;
using System.Collections.Concurrent;
using ExORMDesginer.Services;
using ExORMDesginer.Plugin;
namespace ExORMDesginer.UserControls.Dialogs
{
    public class EntityInfomationDialogInfo : BusinessInfoBase<EntityInfomationDialogInfo>
    {
        IDatabaseDescriptionWriter descWriter;

        public EntityInfomationDialogInfo()
        {
            var dms = ServiceManager.GetService<DatabaseMetaService>();
            descWriter = DatabaseDescriptionWriterFactory.Create(dms.SQLType);
            descWriter.ConnectionString = dms.ConnectionString;
            
            descWriter.ColumnsDescription = new List<ColumnsDescriptionInfo>();
            DbEntity.DisplayNameProperty.ValueChanged += new EventHandler<ExtendPropertyValueChangedArgs>(DisplayNameProperty_ValueChanged);
            DbProperty.DisplayNameProperty.ValueChanged += new EventHandler<ExtendPropertyValueChangedArgs>(DisplayNameProperty_ValueChanged);
        }

      

        public async override void OnLoad()
        {
            EntityInfo = Info;
            descWriter.TableName = EntityInfo.Name;
            base.OnLoad();
        }

        /// <summary>
        /// 表描述或字段描述改变事件
        /// </summary>
        private void DisplayNameProperty_ValueChanged(object sender, ExtendPropertyValueChangedArgs e)
        {
            if (e.NewValue != null)
            {
                if (e.Item is DbEntity)
                {
                    descWriter.TableDescription = e.NewValue.ToString();
                }
                else if (e.Item is DbProperty)
                {
                    var property = e.Item as DbProperty;
                    var item = descWriter.ColumnsDescription.FirstOrDefault(c => c.Name == property.Name);
                    if (item != null)
                        item.Description = e.NewValue.ToString();
                    else
                        descWriter.ColumnsDescription.Add(new ColumnsDescriptionInfo() { Name = property.Name, Description = e.NewValue.ToString() });
                }
            }
        }

        public DbEntity Info { set; get; }
        
        public static ExtendProperty EntityInfoProperty = RegisterProperty(v => v.EntityInfo,ObjectRelations.Children);
        /// <summary>
        /// 表实体信息
        /// </summary>
        public DbEntity EntityInfo { set { SetValue(EntityInfoProperty, value); } get { return (DbEntity)GetValue(EntityInfoProperty); } }

        public async void Save()
        {
            descWriter.Write();
        }

    }
}
